<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="快速入门环境准备和安装 安装JDK，至少1.8.0_73以上版本，java -version 下载和解压缩Elasticsearch安装包（https://www.elastic.co/downloads/past-releases/elasticsearch-5-2-0）">
<meta name="keywords" content="ElasticSearch">
<meta property="og:type" content="article">
<meta property="og:title" content="ElasticSearch02-快速入门">
<meta property="og:url" content="http://www.saily.top/2018/06/05/elasticSearch02/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="快速入门环境准备和安装 安装JDK，至少1.8.0_73以上版本，java -version 下载和解压缩Elasticsearch安装包（https://www.elastic.co/downloads/past-releases/elasticsearch-5-2-0）">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.saily.top/img/es/02/es_start.png">
<meta property="og:image" content="http://www.saily.top/img/es/02/kibana_start.png">
<meta property="og:image" content="http://www.saily.top/img/es/02/kibana_health.png">
<meta property="og:image" content="http://www.saily.top/img/es/02/kibana_search01.png">
<meta property="og:image" content="http://www.saily.top/img/es/02/aggs_error.png">
<meta property="og:image" content="http://www.saily.top/img/es/02/aggs_normal.png">
<meta property="og:updated_time" content="2018-06-12T00:57:47.505Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ElasticSearch02-快速入门">
<meta name="twitter:description" content="快速入门环境准备和安装 安装JDK，至少1.8.0_73以上版本，java -version 下载和解压缩Elasticsearch安装包（https://www.elastic.co/downloads/past-releases/elasticsearch-5-2-0）">
<meta name="twitter:image" content="http://www.saily.top/img/es/02/es_start.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/06/05/elasticSearch02/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>ElasticSearch02-快速入门 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/06/05/elasticSearch02/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ElasticSearch02-快速入门
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-05T22:34:18+08:00">6月 5 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/ElasticSearch/" itemprop="url" rel="index"><span itemprop="name">ElasticSearch</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="快速入门"><a href="#快速入门" class="headerlink" title="快速入门"></a>快速入门</h1><h2 id="环境准备和安装"><a href="#环境准备和安装" class="headerlink" title="环境准备和安装"></a>环境准备和安装</h2><ol>
<li>安装JDK，至少1.8.0_73以上版本，java -version</li>
<li>下载和解压缩Elasticsearch安装包（<a href="https://www.elastic.co/downloads/past-releases/elasticsearch-5-2-0）" target="_blank" rel="noopener">https://www.elastic.co/downloads/past-releases/elasticsearch-5-2-0）</a><a id="more"></a></li>
<li><p>启动Elasticsearch：bin\elasticsearch，es本身特点之一就是开箱即用，如果是中小型应用，数据量少，操作不是很复杂的，直接启动就可以用了。</p>
<p> <img src="/img/es/02/es_start.png" alt=""></p>
</li>
<li><p>检查ES是否启动成功：<a href="http://localhost:9200/?pretty" target="_blank" rel="noopener">http://localhost:9200/?pretty</a></p>
 <figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">name: node名称</span><br><span class="line">cluster_name: 集群名称（默认的集群名称就是elasticsearch）</span><br><span class="line">version.number: 5.2.0，es版本号</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"name"</span> : <span class="string">"4onsTYV"</span>,</span><br><span class="line">  <span class="attr">"cluster_name"</span> : <span class="string">"elasticsearch"</span>,</span><br><span class="line">  <span class="attr">"cluster_uuid"</span> : <span class="string">"nKZ9VK_vQdSQ1J0Dx9gx1Q"</span>,</span><br><span class="line">  <span class="attr">"version"</span> : &#123;</span><br><span class="line">    <span class="attr">"number"</span> : <span class="string">"5.2.0"</span>,</span><br><span class="line">    <span class="attr">"build_hash"</span> : <span class="string">"24e05b9"</span>,</span><br><span class="line">    <span class="attr">"build_date"</span> : <span class="string">"2017-01-24T19:52:35.800Z"</span>,</span><br><span class="line">    <span class="attr">"build_snapshot"</span> : <span class="literal">false</span>,</span><br><span class="line">    <span class="attr">"lucene_version"</span> : <span class="string">"6.4.0"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"tagline"</span> : <span class="string">"You Know, for Search"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>修改集群名称：elasticsearch.yml</p>
<p> 修改<code>elasticsearch.yml</code>里面的<code>cluster.name: my-application</code>即可。</p>
</li>
<li><p>下载和解压缩Kibana安装包，使用里面的开发界面，去操作elasticsearch，作为我们学习es知识点的一个主要的界面入口</p>
<p> <a href="https://www.elastic.co/downloads/past-releases/kibana-5-2-0" target="_blank" rel="noopener">https://www.elastic.co/downloads/past-releases/kibana-5-2-0</a></p>
<p> <img src="/img/es/02/kibana_start.png" alt=""></p>
<p> 访问<a href="http://localhost:5601/，使用devtools进行测试和开发" target="_blank" rel="noopener">http://localhost:5601/，使用devtools进行测试和开发</a></p>
<p> <img src="/img/es/02/kibana_health.png" alt="GET _cluster/health">    </p>
</li>
</ol>
<h2 id="hello-world"><a href="#hello-world" class="headerlink" title="hello world"></a>hello world</h2><p>学习一门新技术，搭建好环境后第一件事当然是做个helloworld的demo，我们来做个crud</p>
<h3 id="document数据格式"><a href="#document数据格式" class="headerlink" title="document数据格式"></a>document数据格式</h3><ol>
<li>es的数据结构存储模式，熟悉mongodb的人应该知道，他们的数据结构是差不多的，都是面向文档的，一条数据就是一个json。</li>
<li>对象数据存储到数据库中，只能拆解开来，变为扁平的多张表，每次查询的时候还得还原回对象格式，相当麻烦。</li>
<li>ES是面向文档的，文档中存储的数据结构，与面向对象的数据结构是一样的，基于这种文档数据结构，es可以提供复杂的索引，全文检索，分析聚合等功能</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> String email;</span><br><span class="line">  <span class="keyword">private</span> String firstName;</span><br><span class="line">  <span class="keyword">private</span> String lastName;</span><br><span class="line">  <span class="keyword">private</span> EmployeeInfo info;</span><br><span class="line">  <span class="keyword">private</span> Date joinDate;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">EmployeeInfo</span> </span>&#123;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">private</span> String bio; <span class="comment">// 性格</span></span><br><span class="line">  <span class="keyword">private</span> Integer age;</span><br><span class="line">  <span class="keyword">private</span> String[] interests; <span class="comment">// 兴趣爱好</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">EmployeeInfo info = <span class="keyword">new</span> EmployeeInfo();</span><br><span class="line">info.setBio(<span class="string">"curious and modest"</span>);</span><br><span class="line">info.setAge(<span class="number">30</span>);</span><br><span class="line">info.setInterests(<span class="keyword">new</span> String[]&#123;<span class="string">"bike"</span>, <span class="string">"climb"</span>&#125;);</span><br><span class="line"></span><br><span class="line">Employee employee = <span class="keyword">new</span> Employee();</span><br><span class="line">employee.setEmail(<span class="string">"zhangsan@sina.com"</span>);</span><br><span class="line">employee.setFirstName(<span class="string">"san"</span>);</span><br><span class="line">employee.setLastName(<span class="string">"zhang"</span>);</span><br><span class="line">employee.setInfo(info);</span><br><span class="line">employee.setJoinDate(<span class="keyword">new</span> Date());</span><br></pre></td></tr></table></figure>
<p>上述代码，在mysql中，肯定就是两张表：employee表，employee_info表，将employee对象的数据重新拆开来，变成Employee数据和EmployeeInfo数据<br>employee表：email，first_name，last_name，join_date，4个字段<br>employee_info表：bio，age，interests，3个字段；此外还有一个外键字段，比如employee_id，关联着employee表</p>
<h3 id="demo背景"><a href="#demo背景" class="headerlink" title="demo背景"></a>demo背景</h3><p>有一个电商网站，需要为其基于ES构建一个后台系统，提供以下功能：</p>
<ol>
<li>对商品信息进行CRUD（增删改查）操作</li>
<li>执行简单的结构化查询</li>
<li>可以执行简单的全文检索，以及复杂的phrase（短语）检索</li>
<li>对于全文检索的结果，可以进行高亮显示</li>
<li>对数据进行简单的聚合分析</li>
</ol>
<h3 id="简单的集群管理"><a href="#简单的集群管理" class="headerlink" title="简单的集群管理"></a>简单的集群管理</h3><h4 id="快速检查集群的健康状况"><a href="#快速检查集群的健康状况" class="headerlink" title="快速检查集群的健康状况"></a>快速检查集群的健康状况</h4><p>es提供了一套api，叫做cat api，可以查看es中各种各样的数据</p>
<p><code>GET /_cat/health?v</code></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">epoch      timestamp cluster       status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent</span><br><span class="line">1528602515 11:48:35  elasticsearch yellow          1         1      1   1    0    0        1             0                  -                 50.0%</span><br></pre></td></tr></table></figure>
<p><strong>如何快速了解集群的健康状况？green、yellow、red？</strong></p>
<ul>
<li>green：每个索引的primary shard和replica shard都是active状态的</li>
<li>yellow：每个索引的primary shard都是active状态的，但是部分replica shard不是active状态，处于不可用的状态</li>
<li>red：不是所有索引的primary shard都是active状态的，部分索引有数据丢失了</li>
</ul>
<p>为什么现在会处于一个yellow状态？</p>
<p>我们现在就一个笔记本电脑，就启动了一个es进程，相当于就只有一个node。现在es中有一个index，就是kibana自己内置建立的index。由于默认的配置是给每个index分配5个primary shard和5个replica shard，而且primary shard和replica shard不能在同一台机器上（为了容错）。现在kibana自己建立的index是1个primary shard和1个replica shard。当前就一个node，所以只有1个primary shard被分配了和启动了，但是一个replica shard没有第二台机器去启动。</p>
<p>做一个小实验：此时只要启动第二个es进程，就会在es集群中有2个node，然后那1个replica shard就会自动分配过去，然后cluster status就会变成green状态。</p>
<h4 id="快速查看集群中有哪些索引"><a href="#快速查看集群中有哪些索引" class="headerlink" title="快速查看集群中有哪些索引"></a>快速查看集群中有哪些索引</h4><p>GET /_cat/indices?v</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">health status index   uuid                   pri rep docs.count docs.deleted store.size pri.store.size</span><br><span class="line">yellow open   .kibana T5J6wa4FSy6ErH1zTOmIEg   1   1          1            0      3.1kb          3.1kb</span><br></pre></td></tr></table></figure>
<h4 id="简单的索引操作"><a href="#简单的索引操作" class="headerlink" title="简单的索引操作"></a>简单的索引操作</h4><p>创建索引：PUT /test_index?pretty</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size</span><br><span class="line">yellow open   test_index cyS7pUwcQKmvTFtUCGNgHg   5   1          0            0       650b           650b</span><br><span class="line">yellow open   .kibana    T5J6wa4FSy6ErH1zTOmIEg   1   1          1            0      3.1kb          3.1kb</span><br><span class="line">```	</span><br><span class="line"></span><br><span class="line">删除索引：DELETE /test_index?pretty</span><br><span class="line"></span><br><span class="line">```text</span><br><span class="line">health status index   uuid                   pri rep docs.count docs.deleted store.size pri.store.size</span><br><span class="line">yellow open   .kibana T5J6wa4FSy6ErH1zTOmIEg   1   1          1            0      3.1kb          3.1kb</span><br></pre></td></tr></table></figure>
<h3 id="商品的CRUD操作"><a href="#商品的CRUD操作" class="headerlink" title="商品的CRUD操作"></a>商品的CRUD操作</h3><h4 id="新增商品：新增文档，建立索引"><a href="#新增商品：新增文档，建立索引" class="headerlink" title="新增商品：新增文档，建立索引"></a>新增商品：新增文档，建立索引</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">PUT /ecommerce/product/1</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"name"</span> : <span class="string">"gaolujie yagao"</span>,</span><br><span class="line">    <span class="attr">"desc"</span> :  <span class="string">"gaoxiao meibai"</span>,</span><br><span class="line">    <span class="attr">"price"</span> :  <span class="number">30</span>,</span><br><span class="line">    <span class="attr">"producer"</span> :      <span class="string">"gaolujie producer"</span>,</span><br><span class="line">    <span class="attr">"tags"</span>: [ <span class="string">"meibai"</span>, <span class="string">"fangzhu"</span> ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"_index"</span>: <span class="string">"ecommerce"</span>,</span><br><span class="line">  <span class="attr">"_type"</span>: <span class="string">"product"</span>,</span><br><span class="line">  <span class="attr">"_id"</span>: <span class="string">"1"</span>,</span><br><span class="line">  <span class="attr">"_version"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"result"</span>: <span class="string">"created"</span>,</span><br><span class="line">  <span class="attr">"_shards"</span>: &#123;</span><br><span class="line">    <span class="attr">"total"</span>: <span class="number">2</span>,</span><br><span class="line">    <span class="attr">"successful"</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">"failed"</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"created"</span>: <span class="literal">true</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">PUT /ecommerce/product/2</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"name"</span> : <span class="string">"jiajieshi yagao"</span>,</span><br><span class="line">    <span class="attr">"desc"</span> :  <span class="string">"youxiao fangzhu"</span>,</span><br><span class="line">    <span class="attr">"price"</span> :  <span class="number">25</span>,</span><br><span class="line">    <span class="attr">"producer"</span> :      <span class="string">"jiajieshi producer"</span>,</span><br><span class="line">    <span class="attr">"tags"</span>: [ <span class="string">"fangzhu"</span> ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">PUT /ecommerce/product/3</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"name"</span> : <span class="string">"zhonghua yagao"</span>,</span><br><span class="line">    <span class="attr">"desc"</span> :  <span class="string">"caoben zhiwu"</span>,</span><br><span class="line">    <span class="attr">"price"</span> :  <span class="number">40</span>,</span><br><span class="line">    <span class="attr">"producer"</span> :      <span class="string">"zhonghua producer"</span>,</span><br><span class="line">    <span class="attr">"tags"</span>: [ <span class="string">"qingxin"</span> ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="查询商品：检索文档"><a href="#查询商品：检索文档" class="headerlink" title="查询商品：检索文档"></a>查询商品：检索文档</h4><p>GET /index/type/id</p>
<p>GET /ecommerce/product/1</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"_index"</span>: <span class="string">"ecommerce"</span>,</span><br><span class="line">  <span class="attr">"_type"</span>: <span class="string">"product"</span>,</span><br><span class="line">  <span class="attr">"_id"</span>: <span class="string">"1"</span>,</span><br><span class="line">  <span class="attr">"_version"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"found"</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="attr">"_source"</span>: &#123;</span><br><span class="line">    <span class="attr">"name"</span>: <span class="string">"gaolujie yagao"</span>,</span><br><span class="line">    <span class="attr">"desc"</span>: <span class="string">"gaoxiao meibai"</span>,</span><br><span class="line">    <span class="attr">"price"</span>: <span class="number">30</span>,</span><br><span class="line">    <span class="attr">"producer"</span>: <span class="string">"gaolujie producer"</span>,</span><br><span class="line">    <span class="attr">"tags"</span>: [</span><br><span class="line">      <span class="string">"meibai"</span>,</span><br><span class="line">      <span class="string">"fangzhu"</span></span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">```	</span><br><span class="line">	#### 修改商品：替换文档</span><br><span class="line"></span><br><span class="line">```json</span><br><span class="line">PUT /ecommerce/product/1</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"name"</span> : <span class="string">"jiaqiangban gaolujie yagao"</span>,</span><br><span class="line">    <span class="attr">"desc"</span> :  <span class="string">"gaoxiao meibai"</span>,</span><br><span class="line">    <span class="attr">"price"</span> :  <span class="number">30</span>,</span><br><span class="line">    <span class="attr">"producer"</span> :      <span class="string">"gaolujie producer"</span>,</span><br><span class="line">    <span class="attr">"tags"</span>: [ <span class="string">"meibai"</span>, <span class="string">"fangzhu"</span> ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"_index"</span>: <span class="string">"ecommerce"</span>,</span><br><span class="line">  <span class="attr">"_type"</span>: <span class="string">"product"</span>,</span><br><span class="line">  <span class="attr">"_id"</span>: <span class="string">"1"</span>,</span><br><span class="line">  <span class="attr">"_version"</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="attr">"result"</span>: <span class="string">"updated"</span>,</span><br><span class="line">  <span class="attr">"_shards"</span>: &#123;</span><br><span class="line">    <span class="attr">"total"</span>: <span class="number">2</span>,</span><br><span class="line">    <span class="attr">"successful"</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">"failed"</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"created"</span>: <span class="literal">false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>替换方式有一个不好，即使必须带上所有的field，才能去进行信息的修改，否则文档的数据结构会被修改。</p>
<h4 id="修改商品：更新文档"><a href="#修改商品：更新文档" class="headerlink" title="修改商品：更新文档"></a>修改商品：更新文档</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">POST /ecommerce/product/1/_update</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"doc"</span>: &#123;</span><br><span class="line">    <span class="attr">"name"</span>: <span class="string">"jiaqiangban gaolujie yagao"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"_index"</span>: <span class="string">"ecommerce"</span>,</span><br><span class="line">  <span class="attr">"_type"</span>: <span class="string">"product"</span>,</span><br><span class="line">  <span class="attr">"_id"</span>: <span class="string">"1"</span>,</span><br><span class="line">  <span class="attr">"_version"</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="attr">"result"</span>: <span class="string">"updated"</span>,</span><br><span class="line">  <span class="attr">"_shards"</span>: &#123;</span><br><span class="line">    <span class="attr">"total"</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">"successful"</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">"failed"</span>: <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="删除商品：删除文档"><a href="#删除商品：删除文档" class="headerlink" title="删除商品：删除文档"></a>删除商品：删除文档</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">DELETE /ecommerce/product/1</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"found"</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="attr">"_index"</span>: <span class="string">"ecommerce"</span>,</span><br><span class="line">  <span class="attr">"_type"</span>: <span class="string">"product"</span>,</span><br><span class="line">  <span class="attr">"_id"</span>: <span class="string">"1"</span>,</span><br><span class="line">  <span class="attr">"_version"</span>: <span class="number">4</span>,</span><br><span class="line">  <span class="attr">"result"</span>: <span class="string">"deleted"</span>,</span><br><span class="line">  <span class="attr">"_shards"</span>: &#123;</span><br><span class="line">    <span class="attr">"total"</span>: <span class="number">2</span>,</span><br><span class="line">    <span class="attr">"successful"</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">"failed"</span>: <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="多种搜索方式"><a href="#多种搜索方式" class="headerlink" title="多种搜索方式"></a>多种搜索方式</h3><p>上面做了CRUD，接下里就是ES里最重要的搜索部分。</p>
<h4 id="query-string-search"><a href="#query-string-search" class="headerlink" title="query string search"></a>query string search</h4><p>搜索全部商品：GET /ecommerce/product/_search</p>
<p><img src="/img/es/02/kibana_search01.png" alt=""></p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">took：耗费了几毫秒</span><br><span class="line">timed_out：是否超时，这里没有</span><br><span class="line">_shards：数据拆成了5个分片，所以对于搜索请求，会分配所有的primary shard（或者是它的某个replica shard）</span><br><span class="line">hits.total：查询结果的数量，3个document</span><br><span class="line">hits.max_score：score的含义，就是document对于一个search的相关度的匹配分数，越相关，就越匹配，分数也高</span><br><span class="line">hits.hits：包含了匹配搜索的document的详细数据</span><br></pre></td></tr></table></figure>
<p>query string search的由来，因为search参数都是以http请求的query string来附带的(也就是?后面的)</p>
<p>搜索商品名称中包含yagao的商品，而且按照售价降序排序：</p>
<p><code>GET /ecommerce/product/_search?q=name:yagao&amp;sort=price:desc</code></p>
<p>适用于临时的在命令行使用一些工具，比如curl，快速的发出请求，来检索想要的信息；但是如果查询请求很复杂，是很难去构建的。在生产环境中，几乎很少使用query string search</p>
<h4 id="query-DSL"><a href="#query-DSL" class="headerlink" title="query DSL"></a>query DSL</h4><p>DSL：Domain Specified Language，特定领域的语言。<br>http request body：请求体，可以用json的格式来构建查询语法，比较方便，可以构建各种复杂的语法，比query string search肯定强大多了</p>
<p><strong>查询所有的商品</strong></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"query"</span>: &#123; <span class="attr">"match_all"</span>: &#123;&#125; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>查询名称包含yagao的商品，同时按照价格降序排序</strong></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"query"</span> : &#123;</span><br><span class="line">        <span class="attr">"match"</span> : &#123;</span><br><span class="line">            <span class="attr">"name"</span> : <span class="string">"yagao"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">"sort"</span>: [</span><br><span class="line">        &#123; <span class="attr">"price"</span>: <span class="string">"desc"</span> &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>分页查询商品，总共3条商品，假设每页就显示1条商品，现在显示第2页，所以就查出来第2个商品</strong></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"query"</span>: &#123; <span class="attr">"match_all"</span>: &#123;&#125; &#125;,</span><br><span class="line">  <span class="attr">"from"</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">"size"</span>: <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>指定要查询出来商品的名称和价格就可以</strong></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"query"</span>: &#123; <span class="attr">"match_all"</span>: &#123;&#125; &#125;,</span><br><span class="line">  <span class="attr">"_source"</span>: [<span class="string">"name"</span>, <span class="string">"price"</span>]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>更加适合生产环境的使用，可以构建复杂的查询。</p>
<h4 id="query-filter"><a href="#query-filter" class="headerlink" title="query filter"></a>query filter</h4><p>搜索商品名称包含yagao，而且售价大于25元的商品</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"query"</span> : &#123;</span><br><span class="line">        <span class="attr">"bool"</span> : &#123;</span><br><span class="line">            <span class="attr">"must"</span> : &#123;</span><br><span class="line">                <span class="attr">"match"</span> : &#123;</span><br><span class="line">                    <span class="attr">"name"</span> : <span class="string">"yagao"</span> </span><br><span class="line">                &#125;</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="attr">"filter"</span> : &#123;</span><br><span class="line">                <span class="attr">"range"</span> : &#123;</span><br><span class="line">                    <span class="attr">"price"</span> : &#123; <span class="attr">"gt"</span> : <span class="number">25</span> &#125; </span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="full-text-search（全文检索）"><a href="#full-text-search（全文检索）" class="headerlink" title="full-text search（全文检索）"></a>full-text search（全文检索）</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"query"</span> : &#123;</span><br><span class="line">        <span class="attr">"match"</span> : &#123;</span><br><span class="line">            <span class="attr">"producer"</span> : <span class="string">"yagao producer"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为查询了2个单词，producer这个字段，会先被拆解，建立倒排索引。</p>
<p>在分词以后，只要任意命中其中一个单词，都会被查询出来，如果2个单词都命中会排在前面。</p>
<h4 id="phrase-search（短语搜索）"><a href="#phrase-search（短语搜索）" class="headerlink" title="phrase search（短语搜索）"></a>phrase search（短语搜索）</h4><p>跟全文检索相对应，相反，全文检索会将输入的搜索串拆解开来，去倒排索引里面去一一匹配，只要能匹配上任意一个拆解后的单词，就可以作为结果返回。</p>
<p>phrase search，要求输入的搜索串，必须在指定的字段文本中，完全包含一模一样的，才可以算匹配，才能作为结果返回。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"query"</span> : &#123;</span><br><span class="line">        <span class="attr">"match_phrase"</span> : &#123;</span><br><span class="line">            <span class="attr">"producer"</span> : <span class="string">"yagao producer"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="highlight-search（高亮搜索结果）"><a href="#highlight-search（高亮搜索结果）" class="headerlink" title="highlight search（高亮搜索结果）"></a>highlight search（高亮搜索结果）</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"query"</span> : &#123;</span><br><span class="line">        <span class="attr">"match"</span> : &#123;</span><br><span class="line">            <span class="attr">"producer"</span> : <span class="string">"producer"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">"highlight"</span>: &#123;</span><br><span class="line">        <span class="attr">"fields"</span> : &#123;</span><br><span class="line">            <span class="attr">"producer"</span> : &#123;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="聚合分析快速入门"><a href="#聚合分析快速入门" class="headerlink" title="聚合分析快速入门"></a>聚合分析快速入门</h3><h4 id="计算每个tag下的商品数量"><a href="#计算每个tag下的商品数量" class="headerlink" title="计算每个tag下的商品数量"></a>计算每个tag下的商品数量</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"aggs"</span>: &#123;</span><br><span class="line">    <span class="attr">"group_by_tags"</span>: &#123;</span><br><span class="line">      <span class="attr">"terms"</span>: &#123; <span class="attr">"field"</span>: <span class="string">"tags"</span> &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="/img/es/02/aggs_error.png" alt=""></p>
<p>报错了，text类型的字段默认不支持聚合，得做个操作让它支持聚合，将文本field的fielddata属性设置为true。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">```</span><br><span class="line"></span><br><span class="line">```json</span><br><span class="line">PUT /ecommerce/_mapping/product</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"properties"</span>: &#123;</span><br><span class="line">    <span class="attr">"tags"</span>: &#123;</span><br><span class="line">      <span class="attr">"type"</span>: <span class="string">"text"</span>,</span><br><span class="line">      <span class="attr">"fielddata"</span>: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>再测试一次聚合查询，就好了</p>
<p><img src="/img/es/02/aggs_normal.png" alt=""></p>
<h4 id="对名称中包含yagao的商品，计算每个tag下的商品数量"><a href="#对名称中包含yagao的商品，计算每个tag下的商品数量" class="headerlink" title="对名称中包含yagao的商品，计算每个tag下的商品数量"></a>对名称中包含yagao的商品，计算每个tag下的商品数量</h4><p>在聚合分析的基础上加上条件筛选</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"size"</span>: <span class="number">0</span>,</span><br><span class="line">  <span class="attr">"query"</span>: &#123;</span><br><span class="line">    <span class="attr">"match"</span>: &#123;</span><br><span class="line">      <span class="attr">"name"</span>: <span class="string">"yagao"</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"aggs"</span>: &#123;</span><br><span class="line">    <span class="attr">"all_tags"</span>: &#123;</span><br><span class="line">      <span class="attr">"terms"</span>: &#123;</span><br><span class="line">        <span class="attr">"field"</span>: <span class="string">"tags"</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="先分组，再算每组的平均值，计算每个tag下的商品的平均价格"><a href="#先分组，再算每组的平均值，计算每个tag下的商品的平均价格" class="headerlink" title="先分组，再算每组的平均值，计算每个tag下的商品的平均价格"></a>先分组，再算每组的平均值，计算每个tag下的商品的平均价格</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"size"</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">"aggs"</span> : &#123;</span><br><span class="line">        <span class="attr">"group_by_tags"</span> : &#123;</span><br><span class="line">            <span class="attr">"terms"</span> : &#123; <span class="attr">"field"</span> : <span class="string">"tags"</span> &#125;,</span><br><span class="line">            <span class="attr">"aggs"</span> : &#123;</span><br><span class="line">                <span class="attr">"avg_price"</span> : &#123;</span><br><span class="line">                    <span class="attr">"avg"</span> : &#123; <span class="attr">"field"</span> : <span class="string">"price"</span> &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"took"</span>: <span class="number">22</span>,</span><br><span class="line">  <span class="attr">"timed_out"</span>: <span class="literal">false</span>,</span><br><span class="line">  <span class="attr">"_shards"</span>: &#123;</span><br><span class="line">    <span class="attr">"total"</span>: <span class="number">5</span>,</span><br><span class="line">    <span class="attr">"successful"</span>: <span class="number">5</span>,</span><br><span class="line">    <span class="attr">"failed"</span>: <span class="number">0</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"hits"</span>: &#123;</span><br><span class="line">    <span class="attr">"total"</span>: <span class="number">3</span>,</span><br><span class="line">    <span class="attr">"max_score"</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">"hits"</span>: []</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"aggregations"</span>: &#123;</span><br><span class="line">    <span class="attr">"group_by_tags"</span>: &#123;</span><br><span class="line">      <span class="attr">"doc_count_error_upper_bound"</span>: <span class="number">0</span>,</span><br><span class="line">      <span class="attr">"sum_other_doc_count"</span>: <span class="number">0</span>,</span><br><span class="line">      <span class="attr">"buckets"</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">"key"</span>: <span class="string">"fangzhu"</span>,</span><br><span class="line">          <span class="attr">"doc_count"</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">"avg_price"</span>: &#123;</span><br><span class="line">            <span class="attr">"value"</span>: <span class="number">27.5</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">"key"</span>: <span class="string">"meibai"</span>,</span><br><span class="line">          <span class="attr">"doc_count"</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">"avg_price"</span>: &#123;</span><br><span class="line">            <span class="attr">"value"</span>: <span class="number">30</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">"key"</span>: <span class="string">"qingxin"</span>,</span><br><span class="line">          <span class="attr">"doc_count"</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">"avg_price"</span>: &#123;</span><br><span class="line">            <span class="attr">"value"</span>: <span class="number">40</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="计算每个tag下的商品的平均价格，并且按照平均价格降序排序"><a href="#计算每个tag下的商品的平均价格，并且按照平均价格降序排序" class="headerlink" title="计算每个tag下的商品的平均价格，并且按照平均价格降序排序"></a>计算每个tag下的商品的平均价格，并且按照平均价格降序排序</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">    <span class="attr">"size"</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">"aggs"</span> : &#123;</span><br><span class="line">        <span class="attr">"all_tags"</span> : &#123;</span><br><span class="line">            <span class="attr">"terms"</span> : &#123; <span class="attr">"field"</span> : <span class="string">"tags"</span>, <span class="attr">"order"</span>: &#123; <span class="attr">"avg_price"</span>: <span class="string">"desc"</span> &#125; &#125;,</span><br><span class="line">            <span class="attr">"aggs"</span> : &#123;</span><br><span class="line">                <span class="attr">"avg_price"</span> : &#123;</span><br><span class="line">                    <span class="attr">"avg"</span> : &#123; <span class="attr">"field"</span> : <span class="string">"price"</span> &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="按照指定的价格范围区间进行分组，然后在每组内再按照tag进行分组，最后再计算每组的平均价格"><a href="#按照指定的价格范围区间进行分组，然后在每组内再按照tag进行分组，最后再计算每组的平均价格" class="headerlink" title="按照指定的价格范围区间进行分组，然后在每组内再按照tag进行分组，最后再计算每组的平均价格"></a>按照指定的价格范围区间进行分组，然后在每组内再按照tag进行分组，最后再计算每组的平均价格</h4><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">GET /ecommerce/product/_search</span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">"size"</span>: <span class="number">0</span>,</span><br><span class="line">  <span class="attr">"aggs"</span>: &#123;</span><br><span class="line">    <span class="attr">"group_by_price"</span>: &#123;</span><br><span class="line">      <span class="attr">"range"</span>: &#123;</span><br><span class="line">        <span class="attr">"field"</span>: <span class="string">"price"</span>,</span><br><span class="line">        <span class="attr">"ranges"</span>: [</span><br><span class="line">          &#123;</span><br><span class="line">            <span class="attr">"from"</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">"to"</span>: <span class="number">20</span></span><br><span class="line">          &#125;,</span><br><span class="line">          &#123;</span><br><span class="line">            <span class="attr">"from"</span>: <span class="number">20</span>,</span><br><span class="line">            <span class="attr">"to"</span>: <span class="number">40</span></span><br><span class="line">          &#125;,</span><br><span class="line">          &#123;</span><br><span class="line">            <span class="attr">"from"</span>: <span class="number">40</span>,</span><br><span class="line">            <span class="attr">"to"</span>: <span class="number">50</span></span><br><span class="line">          &#125;</span><br><span class="line">        ]</span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="attr">"aggs"</span>: &#123;</span><br><span class="line">        <span class="attr">"group_by_tags"</span>: &#123;</span><br><span class="line">          <span class="attr">"terms"</span>: &#123;</span><br><span class="line">            <span class="attr">"field"</span>: <span class="string">"tags"</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">"aggs"</span>: &#123;</span><br><span class="line">            <span class="attr">"average_price"</span>: &#123;</span><br><span class="line">              <span class="attr">"avg"</span>: &#123;</span><br><span class="line">                <span class="attr">"field"</span>: <span class="string">"price"</span></span><br><span class="line">              &#125;</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ElasticSearch/" rel="tag"># ElasticSearch</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/03/elasticSearch01/" rel="next" title="ElasticSearch01-介绍">
                <i class="fa fa-chevron-left"></i> ElasticSearch01-介绍
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/10/hystrix04/" rel="prev" title="Hystrix监控和运维">
                Hystrix监控和运维 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#快速入门"><span class="nav-number">1.</span> <span class="nav-text">快速入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#环境准备和安装"><span class="nav-number">1.1.</span> <span class="nav-text">环境准备和安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#hello-world"><span class="nav-number">1.2.</span> <span class="nav-text">hello world</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#document数据格式"><span class="nav-number">1.2.1.</span> <span class="nav-text">document数据格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#demo背景"><span class="nav-number">1.2.2.</span> <span class="nav-text">demo背景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#简单的集群管理"><span class="nav-number">1.2.3.</span> <span class="nav-text">简单的集群管理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#快速检查集群的健康状况"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">快速检查集群的健康状况</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#快速查看集群中有哪些索引"><span class="nav-number">1.2.3.2.</span> <span class="nav-text">快速查看集群中有哪些索引</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#简单的索引操作"><span class="nav-number">1.2.3.3.</span> <span class="nav-text">简单的索引操作</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#商品的CRUD操作"><span class="nav-number">1.2.4.</span> <span class="nav-text">商品的CRUD操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#新增商品：新增文档，建立索引"><span class="nav-number">1.2.4.1.</span> <span class="nav-text">新增商品：新增文档，建立索引</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#查询商品：检索文档"><span class="nav-number">1.2.4.2.</span> <span class="nav-text">查询商品：检索文档</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#修改商品：更新文档"><span class="nav-number">1.2.4.3.</span> <span class="nav-text">修改商品：更新文档</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#删除商品：删除文档"><span class="nav-number">1.2.4.4.</span> <span class="nav-text">删除商品：删除文档</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多种搜索方式"><span class="nav-number">1.2.5.</span> <span class="nav-text">多种搜索方式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#query-string-search"><span class="nav-number">1.2.5.1.</span> <span class="nav-text">query string search</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#query-DSL"><span class="nav-number">1.2.5.2.</span> <span class="nav-text">query DSL</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#query-filter"><span class="nav-number">1.2.5.3.</span> <span class="nav-text">query filter</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#full-text-search（全文检索）"><span class="nav-number">1.2.5.4.</span> <span class="nav-text">full-text search（全文检索）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#phrase-search（短语搜索）"><span class="nav-number">1.2.5.5.</span> <span class="nav-text">phrase search（短语搜索）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#highlight-search（高亮搜索结果）"><span class="nav-number">1.2.5.6.</span> <span class="nav-text">highlight search（高亮搜索结果）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#聚合分析快速入门"><span class="nav-number">1.2.6.</span> <span class="nav-text">聚合分析快速入门</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#计算每个tag下的商品数量"><span class="nav-number">1.2.6.1.</span> <span class="nav-text">计算每个tag下的商品数量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#对名称中包含yagao的商品，计算每个tag下的商品数量"><span class="nav-number">1.2.6.2.</span> <span class="nav-text">对名称中包含yagao的商品，计算每个tag下的商品数量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#先分组，再算每组的平均值，计算每个tag下的商品的平均价格"><span class="nav-number">1.2.6.3.</span> <span class="nav-text">先分组，再算每组的平均值，计算每个tag下的商品的平均价格</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#计算每个tag下的商品的平均价格，并且按照平均价格降序排序"><span class="nav-number">1.2.6.4.</span> <span class="nav-text">计算每个tag下的商品的平均价格，并且按照平均价格降序排序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#按照指定的价格范围区间进行分组，然后在每组内再按照tag进行分组，最后再计算每组的平均价格"><span class="nav-number">1.2.6.5.</span> <span class="nav-text">按照指定的价格范围区间进行分组，然后在每组内再按照tag进行分组，最后再计算每组的平均价格</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
